﻿using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Demo.Net.IdentityServer.IdentityServer
{
    public class SeedDataController : Controller
    {
        private readonly ConfigurationDbContext _configurationDb;
        private readonly PersistedGrantDbContext _persistedGrantDb;
        private readonly IdentityServer _identityServer;

        public SeedDataController(IServiceProvider serviceProvider)
        {
            _configurationDb = serviceProvider.GetRequiredService<ConfigurationDbContext>();
            _persistedGrantDb = serviceProvider.GetRequiredService<PersistedGrantDbContext>();
            _identityServer = IdentityViewModel.IdentityServer;
        }

        public IActionResult Ensure()
        {
            _configurationDb.Database.Migrate();
            _persistedGrantDb.Database.Migrate();

            foreach (var client in _identityServer.Clients)
            {
                if (_configurationDb.Clients.Any(e => e.ClientId == client.ClientId))
                {
                    continue;
                }
                client.ToEntity();
                _configurationDb.Clients.Add(client.ToEntity());
            }

            foreach (var api in _identityServer.ApiScopes)
            {
                if (_configurationDb.ApiScopes.Any(e => e.Name == api.Name))
                {
                    continue;
                }

                _configurationDb.ApiScopes.Add(api.ToEntity());
            }

            foreach (var api in _identityServer.ApiResources)
            {
                if (_configurationDb.ApiResources.Any(e => e.Name == api.Name))
                {
                    continue;
                }

                _configurationDb.ApiResources.Add(api.ToEntity());
            }

            foreach (var id in _identityServer.IdentityResources)
            {
                if (_configurationDb.IdentityResources.Any(e => e.Name == id.Name))
                {
                    continue;
                }

                _configurationDb.IdentityResources.Add(id.ToEntity());
            }

            _configurationDb.SaveChanges();

            return Content("成功");
        }
    }
}
